﻿using SuperFx;
using SuperMoney.Datas.DbModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperMoney.Datas
{
	/// <summary>
	/// 广告记录数据服务。
	/// </summary>
	public class AdRecordDbService
	{
		/// <summary>
		/// 广告记录数据服务实例。
		/// </summary>
		public static readonly AdRecordDbService Instance = new AdRecordDbService();

		/// <summary>
		/// 创建广告记录。
		/// </summary>
		/// <param name="fields"></param>
		/// <returns></returns>
		public AdRecord Create(AdRecord adRecord)
		{
			adRecord.AddTime = DateTime.Now;
			adRecord.UpdateTime = DateTime.Now;
			using (var db = MRMDB.New())
			{
				db.AdRecordSet.Add(adRecord);
				db.SaveChanges();
			}
			return adRecord;
		}

		/// <summary>
		/// 根据广告订单编号获取广告记录。
		/// </summary>
		/// <param name="adPlatform">广告平台。</param>
		/// <param name="adOrderId">广告订单编号。</param>
		/// <returns></returns>
		public AdRecord Get(string adPlatform, string adOrderId)
		{
			using (var db = MRMDB.New())
			{
				return db.AdRecordSet.Where(p => p.AdPlatform == adPlatform && p.AdOrderId == adOrderId).SingleOrDefault();
			}
		}

		/// <summary>
		/// 判断广告订单编号是否存在。
		/// </summary>
		/// <param name="adPlatform">广告平台。</param>
		/// <param name="adOrderId">广告订单编号。</param>
		/// <returns></returns>
		public bool Exists(string adPlatform, string adOrderId)
		{
			using (var db = MRMDB.New())
			{
				return db.AdRecordSet.Where(p => p.AdPlatform == adPlatform && p.AdOrderId == adOrderId).Count() > 0;
			}
		}

		/// <summary>
		/// 获取广告记录。
		/// </summary>
		/// <param name="count">每页条数。</param>
		/// <param name="page">当前页码。</param>
		/// <returns></returns>
		public List<AdRecord> GetList(int count, int page)
		{
			using (var db = MRMDB.New())
			{
				int skip = (page - 1) * count;
				return db.AdRecordSet.OrderByDescending(p => p.Id).Skip(skip).Take(count).ToList();
			}
		}

		/// <summary>
		/// 获取广告记录。
		/// </summary>
		/// <param name="deviceId">设备编号。</param>
		/// <param name="count">每页条数。</param>
		/// <param name="page">当前页码。</param>
		/// <returns></returns>
		public List<AdRecord> GetList(string deviceId, int count, int page)
		{
			using (var db = MRMDB.New())
			{
				int skip = (page - 1) * count;
				return db.AdRecordSet.Where(p => p.DeviceId == deviceId).OrderByDescending(p=>p.Id).Skip(skip).Take(count).ToList();
			}
		}
	}
}
